package com.travel.yang.aop;

import com.travel.yang.bean.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component      //确保被Spring扫描到
@Aspect         //定义切面类
public class LogAop {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private final static Logger logger = LoggerFactory.getLogger(LogAop.class);

    @Pointcut("execution(* com.travel.yang.controller.backstage.*.*(..))")          //切入点
    public void pointCut(){
    }

    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint){
        //记录访问时间
        Date date = new Date();
        request.setAttribute("visitTime", date);
    }

    @After("pointCut()")
    public void doAfter(){
        Log log = new Log();
        Date visitTime = (Date)request.getAttribute("visitTime");     //访问时间
        Date now = new Date();
        int executionTime = (int) (now.getTime() - visitTime.getTime());        //访问时长
        String ip = request.getRemoteAddr();        //访问ip
        String url = request.getRequestURI();       //访问路径
        //获取Security里面的User对象
        Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user instanceof User){
            String username = ((User) user).getUsername();
            log.setUsername(username);
        }
        log.setExecutionTime(executionTime);
        log.setIp(ip);
        log.setUrl(url);
        log.setVisitTime(visitTime);

        logger.info(log.toString());
    }

    @AfterThrowing(pointcut = "pointCut()", throwing = "ex")            //异常日志
    public void doAfterThrowing(Throwable ex){
        Log log = new Log();
        Date visitTime = (Date)request.getAttribute("visitTime");     //访问时间
        Date now = new Date();
        int executionTime = (int) (now.getTime() - visitTime.getTime());        //访问时长
        String ip = request.getRemoteAddr();        //访问ip
        String url = request.getRequestURI();       //访问路径
        //获取Security里面的User对象
        Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user instanceof User){
            String username = ((User) user).getUsername();
            log.setUsername(username);
        }
        log.setExecutionTime(executionTime);
        log.setIp(ip);
        log.setUrl(url);
        log.setVisitTime(visitTime);

        //异常信息
        String exMessage = ex.getMessage();
        log.setExceptionMessage(exMessage);

        logger.info(log.toString());
    }
}
